import 'package:sl_doclever/src/doclever/sl_doc_config.dart';
import 'package:sl_doclever/src/doclever/sl_node.dart';
import 'package:core_extension/core_extension.dart';

class SLDocData {
  final String name;
  final String url;
  String urlLastName;
  final String remark;
  final String method;
  final List<SLNode> header;
  final List<SLNode> queryParam;
  final List<SLNode> outParam;
  final List<SLNode> rawJSON;

  final Map headerJson;
  final Map queryParamJson;
  final Map outParamJson;
  final Map rawJSONJson;

  SLDocData({
    this.headerJson,
    this.queryParamJson,
    this.outParamJson,
    this.rawJSONJson,
    this.rawJSON,
    this.outParam,
    this.header,
    this.queryParam,
    this.name,
    this.url,
    this.remark,
    this.method,
  }) {
    urlLastName = url.split('/').last.split('.').first;

    updateCodeType(header, urlLastName);
    updateCodeType(queryParam, urlLastName);
    updateCodeType(rawJSON, urlLastName);
    updateCodeType(outParam, urlLastName);
  }

  @override
  String toString() {
    return 'name:$name\n'
        'url:$url\n'
        'urlLastName:$urlLastName\n'
        'remark:$remark\n'
        'method:$method\n'
        'header:${header.toString()}\n'
        'queryParam:${queryParam.toString()}\n'
        'rawJSON:${rawJSON.toString()}\n'
        'outParam:${outParam.toString()}\n'
        'headerJson:$headerJson\n'
        'queryParamJson:$queryParamJson\n'
        'outParamJson:$outParamJson\n'
        'rawJSONJson:$rawJSONJson\n';
  }

  /// 所有节点名称
  /// ```
  /// [_ROOT_, data, resultList]
  /// ```
  List<SLNode> allNodesName(List<SLNode> nodes) {
    var retNodes = <SLNode>[];

    for (var node in nodes) {
      var canAdd = true;

      for (var item in retNodes) {
        if (item.faterNode == node.faterNode) {
          canAdd = false;
          break;
        }
      }

      if (canAdd) retNodes.add(node);
    }

    return retNodes;
  }

  /// 是否存在子属性，还是空
  bool hasSubNodes(List<SLNode> nodes, String name) {
    var hasNode = false;

    for (var node in nodes) {
      if (node.faterNode == name) {
        hasNode = true;
        break;
      }
    }

    return hasNode;
  }

  /// 更新code类型
  void updateCodeType(List<SLNode> nodes, String lastName) {
    if (nodes == null || nodes.isEmpty) return;

    nodes.forEach((node) {
      node.codeType = SLDocConfig().prefix +
          lastName.sl_capitalize() +
          ((node.faterNode == SLDocConfig().root)
              ? ''
              : node.faterNode.sl_capitalize());
    });
  }
}
